<?php

function SQLGrantyEvent($event_id) {
    $sql = sprintf("SELECT projects.* FROM SimpleEventsInProjects, projects "
            . "WHERE SimpleEventsInProjects.event = '%d' AND projects.id=SimpleEventsInProjects.project", $event_id);
    //echo $sql;
    $res = mysql_query($sql);
    $out = array();
    while ($row = mysql_fetch_assoc($res)) { //print_r($row);
        $out[] = $row;
    }
    mysql_free_result($res);
    return($out);
}

function SQLGrantyPerson($person_id=null) {
    if ($person_id==null){ // all grants
        $sql = sprintf( "SELECT id as project, Name FROM `projects`");
    } else { // grants of seleceted person
        $sql = sprintf( "SELECT PeopleInProjects.project, projects.Name FROM `PeopleInProjects`, `projects`"
        ." WHERE `PeopleInProjects`.person = '%s' AND `PeopleInProjects`.`project`=projects.id", $person_id);
    }
    //echo $sql;
    $res = mysql_query($sql);
    $out = array();
    while ($row = mysql_fetch_assoc($res)) { //print_r($row);
        $out[] = $row;
    }
    mysql_free_result($res);
    return($out);
}

function date2SQL($d){
        // http://php.vrana.cz/prevod-data-z-ceskeho-formatu.php
    if (preg_match('~^([0-9]+)\\.([0-9]+)\\.([0-9]+)$~', $d, $match)) {
        return(sprintf("%d-%02d-%02d", $match[3], $match[2], $match[1]));
    } ;
}

function SetVisibleInterval($m, $y) {
    $_SESSION['view']['current'] = array('M'=>$m, 'Y'=>$y);
};


function SetVisiblePerson($i=0) {
    if (! AmIAdmin()) echo ("Pouze pro administrátory");
    else {
        if ($i==0) unset($_SESSION['pinfo']);
        else {
            $_SESSION['pinfo'] =  $_SESSION['Global']['People'][$i];
            $_SESSION['pinfo']['granty'] = SQLGrantyPerson($i); // add list af all projects
        }
        }
        //echo "Změněn člověk : ".$i;
}

function AmIAdmin($level=1) {
    $h = $_SESSION['linfo']['is_admin'];
    return (isset($h) && $h<>null && $h>=$level);
};

function IfAdmin($result, $level=1) {
    if (AmIAdmin($level)) return $result;
}

function EchoWithPinfo($result) {
    if (isset($_SESSION['pinfo'])) echo $result;
}
function EchoWithoutPinfo($result) {
    if (! isset($_SESSION['pinfo'])) echo $result;
}

// Person name parsing
function PersonName($p) {
    return sprintf("%s %s", $p[':first'], $p[':last']);
}
function PersonNameLast($p) {
    return sprintf("%s", $p[':last']);
}
?>
